/* eslint-disable @typescript-eslint/no-explicit-any */
import { defineStore } from "pinia"
// import { ref } from "vue"
import { getCurrentUser } from '@/api/user'
import defaultAvatar from '@/assets/images/default_avatar.jpeg'

export const useLoginUserStore = defineStore('login-user-store', {
    state: () => ({
        loginStatus: 0,
        uid: 0,
        username: '',
        nickname: '',
        avatar: ''
    }),
    getters: {
        // doubleCount: (state) => state.count * 2,
        getNickname: (state) => state.nickname || state.username,
        getUid: (state) => {
            const str = state.uid.toString()
            return Array(Math.max(8 - str.length, 0)).fill('0').join('') + str
        },
        getAvatar: (state) => {
            if (state.loginStatus && state.avatar) {
                try {
                    // 动态导入用户头像
                    // console.log('https://127.0.0.1:8080' + loginUserStore.loginUser.info.avatar_path)
                    return ((window as any).APP_CONFIG?.API_BASE_URL || '') + state.avatar
                } catch (err) {
                    console.error('头像加载失败:', err)
                    return defaultAvatar // 加载失败时显示默认头像
                }
            } else {
                return defaultAvatar
            }
        }
    },
    actions: {
        async fetchLoginUser() {
            const res = await getCurrentUser()
            if (res.data.code === 0 && res.data.data) {
                this.uid = res.data.data.uid
                this.username = res.data.data.username
                this.nickname = res.data.data.nickname
                this.avatar = res.data.data.avatar_path
                this.loginStatus++
            }
        },
        setNickname(nickname: string) {
            this.nickname = nickname
        },
        logout() {
            this.loginStatus = 0
            this.uid = 0
            this.avatar = ''
            this.username = ''
            this.nickname = ''
            localStorage.setItem('token', '')
        }

    },
})